<?php
// +----------------------------------------------------------------------
// | RXThinkCMF敏捷开发框架 [ 赋能开发者，助力企业发展 ]
// +----------------------------------------------------------------------
// | 版权所有 2018~2023 南京RXThinkCMF研发中心
// +----------------------------------------------------------------------
// | Licensed LGPL-3.0 RXThinkCMF并不是自由软件，未经许可禁止去掉相关版权
// +----------------------------------------------------------------------
// | 官方网站: https://www.rxthink.cn
// +----------------------------------------------------------------------
// | Author: @牧羊人 团队荣誉出品
// +----------------------------------------------------------------------
// | 版权和免责声明:
// | 本团队对该软件框架产品拥有知识产权（包括但不限于商标权、专利权、著作权、商业秘密等）
// | 均受到相关法律法规的保护，任何个人、组织和单位不得在未经本团队书面授权的情况下对所授权
// | 软件框架产品本身申请相关的知识产权，禁止用于任何违法、侵害他人合法权益等恶意的行为，禁
// | 止用于任何违反我国法律法规的一切项目研发，任何个人、组织和单位用于项目研发而产生的任何
// | 意外、疏忽、合约毁坏、诽谤、版权或知识产权侵犯及其造成的损失 (包括但不限于直接、间接、
// | 附带或衍生的损失等)，本团队不承担任何法律责任，本软件框架禁止任何单位和个人、组织用于
// | 任何违法、侵害他人合法利益等恶意的行为，如有发现违规、违法的犯罪行为，本团队将无条件配
// | 合公安机关调查取证同时保留一切以法律手段起诉的权利，本软件框架只能用于公司和个人内部的
// | 法律所允许的合法合规的软件产品研发，详细声明内容请阅读《框架免责声明》附件；
// +----------------------------------------------------------------------

namespace app\admin\service;


use app\admin\model\Clss;
use app\admin\model\Member;

/**
 * 班级管理-服务类
 * @author 牧羊人
 * @since: 2023/07/31
 * Class ClssService
 * @package app\admin\service
 */
class ClssService extends BaseService
{
    /**
     * 构造函数
     * LevelService constructor.
     */
    public function __construct()
    {
        $this->model = new Clss();
    }

	/**
     * 获取数据列表
     * @return array
     * @since 2023/07/31
     * @author 牧羊人
     */
    public function getList()
    {
        $param = request()->param();

        // 查询条件
        $map = [];

		 // 所属组织
        $organization = isset($param['organization']) ? (int)$param['organization'] : '';
        if ($organization) {
            $map[] = ['organization', '=', $organization];
        }

        // 所属年级
        $grade = isset($param['grade']) ? (int)$param['grade'] : '';
        if ($grade) {
            $map[] = ['grade', '=', $grade];
        }

        // 所属院系
        $superior = isset($param['superior']) ? (int)$param['superior'] : '';
        if ($superior) {
            $map[] = ['superior', '=', $superior];
        }

        // 所属专业
        $professional = isset($param['professional']) ? (int)$param['professional'] : '';
        if ($professional) {
            $map[] = ['professional', '=', $professional];
        }

	    // 班级名称
        $name = isset($param['name']) ? trim($param['name']) : '';
        if ($name) {
            $map[] = ['name', 'like', "%{$name}%"];
        }

        // 类型
        $stype = isset($param['stype']) ? (int)$param['stype'] : 0;
        if ($stype) {
            $map[] = ['stype', '=', $stype];
        }

	    // 状态
        $status = isset($param['status']) ? (int)$param['status'] : 0;
        if ($status) {
            $map[] = ['status', '=', $status];
        }

        // 更新时间
        $starttime = isset($param['starttime']) ? trim($param['starttime']) : '';
        $endtime = isset($param['endtime']) ? trim($param['endtime']) : '';
        if ($starttime&&$endtime) {
            $map[] = ['update_time', '>= time', $starttime];
            $map[] = ['update_time', '<= time', $endtime];
        }

        return parent::getList($map,'id desc'); // TODO: Change the autogenerated stub
    }

    /**
     * 添加或编辑
     * @return mixed
     * @since 2020/11/19
     * @author 牧羊人
     */
    public function edit()
    {
        // 获取参数
        $argList = func_get_args();
        // 查询条件
        $data = isset($argList[0]) ? $argList[0] : [];
        // 是否打印SQL
        $is_sql = isset($argList[1]) ? $argList[1] : false;
        if (!$data) {
            $data = request()->param();
        }
        $error = '';
        $rowId = $this->model->edit($data, $error, $is_sql);
        if ($rowId) {
            // $thirdid = 0;
            // if (isset($data['id'])) {
            //     $thirdid = \app\admin\model\Clss::where('id',$data['id'])->value('thirdclass');
            // }
            // if (!$thirdid) {
            //     $where = [
            //         ['grade','=',$data['grade']]
            //     ];
            //     $clist = \app\admin\model\Clss::where($where)->order('id ASC')->column('id');
            //     if ($clist) {
            //         $cid = array_search($rowId,$clist)+1;
            //     }else{
            //         $cid = 1;
            //     }
                
                
            //     $incode = \app\admin\model\School::where(['id'=>$data['organization']])->value('code');
            //     $gradeid = \app\admin\model\Grade::where(['id'=>$data['grade']])->value('thirdgrade');
            //     $datas = [
            //         "inviteCode"=>$incode,
            //         "schoolInfo"=>[
            //             ["grade"=>$gradeid,"classList"=>[$cid]]
            //         ]
            //     ];
            //     $results = $this->addClazz($datas);//同步第三方数据
            //     if ($results['code']==200) {
            //         \app\admin\model\Clss::where(['id'=>$rowId])->update(['thirdclass'=>$cid]);
            //     }else{
            //         halt($results);
            //     }
                
            // }
            
            return message();
        }
        return message($error, false);
    }

    /**
     * 获取班级列表
     * @return array
     * @since 2020/11/20
     * @author 牧羊人
     */
    public function getClassList()
    {
        $param = request()->param();
        $where = [];
        $where['mark'] = 1;
        $list = [];
        if (isset($param['yid'])&& $param['yid']>0) {
            $where['superior'] = $param['yid'];
        }
        if (isset($param['gid'])&& $param['gid']>0) {
            $where['grade'] = $param['gid'];
        }
        if (isset($param['pid'])&& $param['pid']>0) {
            $where['professional'] = $param['pid'];
        }
        if (isset($param['stype'])&& $param['stype']>0) {
            $where['stype'] = $param['stype'];
        }
        $list = $this->model->where($where)->cache(12*3600)->select()->toArray();
        return message("操作成功", true, $list);
    }

    /**
     * 获取班级名单分页列表
     * @return array
     * @since 2020/11/20
     * @author 牧羊人
     */
    public function getStuList()
    {
        $param = request()->param();
        $sort = 'id desc';
        $where = [];
        $where[] = ['mark','=',1];
        $list = [];
        if (isset($param['class'])&& $param['class']>0) {
            if ($param['stype']==2) {
                $str = '"'.$param['class'].'"';
                $where[] = ['features', 'like','%'.$str.'%'];
            }else{
                $where[] = ['class', '=',$param['class']];
            }

            $member = new Member();
            $result = $member->where($where)->order($sort)->page(PAGE, PERPAGE)->column("id");
            //$result = $member->where($where)->column("id");
            //$list = $member->where($where)->select()->toArray();
            if (is_array($result)) {
                foreach ($result as $val) {
                    $info = $member->getInfo($val);
                    $list[] = $info;
                }
            }
        }

        //获取数据总数
        $count = $member->where($where)->count();

        //返回结果
        $message = array(
            "msg" => '操作成功',
            "code" => 0,
            "data" => $list,
            "count" => $count,
        );

        return $message;
    }

    /**
     * 获取班级名单列表
     * @return array
     * @since 2020/11/20
     * @author 牧羊人
     */
    public function getStudentsList()
    {
        $param = request()->param();
        $where = [];
        $where[] = ['mark','=',1];
        $list = [];
        if (isset($param['class'])&& $param['class']>0) {
            $str = '"'.$param['class'].'"';
            $where[] = ['features', 'like','%'.$str.'%'];
            $member = new Member();
            $result = $member->where($where)->column("id");
            //$list = $member->where($where)->select()->toArray();
            if (is_array($result)) {
                foreach ($result as $val) {
                    $info = $member->getInfo($val);
                    $list[] = $info;
                }
            }
        }

        return message("操作成功", true, $list);
    }

    /**
     * 保存班级名单
     * @return array
     * @since 2020/11/20
     * @author 牧羊人
     */
    public function saveImportlist()
    {
        $param = request()->param();
        $selectList = json_decode($param['select'],true);
        $member = new Member();
        $clss = new Clss();
        $carr = [];
        // 导入名单前将之前名单数据解除班级绑定
        $fwhere[] = ['features', 'like', '%'.strval($param['class']).'%'];
        $features = $member->where($fwhere)->column('id');
        if ($features) {
            foreach ($features as $vv) {
                // 学员学籍号
                $mmf = $member->where('id',$vv)->find();
                $mfeature = json_decode($mmf['features'],true);
                if (!is_array($mfeature)) {
                    $mfeature = [];
                }else{
                    if ($mfeature[0]=='undefined') {
                        $mfeature = [];
                    }
                }
                if (in_array(strval($param['class']),$mfeature)) {
                    $ffeature = array_diff($mfeature,array(strval($param['class'])));
                    $member->update(['features'=>json_encode(array_values($ffeature))],['id'=>$vv]);
                }
            }
        }
        foreach ($selectList as $vs) {
            $features = json_decode($member->where('id',$vs['id'])->find()['features'],true);
            if (!is_array($features)) {
                $features = [];
            }
            if (!in_array(strval($param['class']),$features)) {
                array_push($features,strval($param['class']));
            }
            $member->update(['features'=>json_encode($features)],['id'=>$vs['id']]);
            array_push($carr,strval($vs['id']));
        }
        $clss->update(['features'=>json_encode($carr)],['id'=>$param['class']]);

        return message("保存成功");
    }

    /**
     * 保存导入班级名单
     * @return array
     * @since 2020/11/20
     * @author 牧羊人
     */
    public function saveImportroll()
    {
        $param = request()->param();
        $rolllist = $param['rolllist'];
        $dnum = 0;//导入几条
        $wnum = 0;//导入失败几条
        $member = new Member();
        $clss = new Clss();
        $carr = [];
        foreach ($rolllist as $vs) {
            $mm = $member->where('roll',$vs)->find();

            if ($mm) {
                $features = json_decode($mm['features'],true);
                if (!is_array($features)) {
                    $features = [];
                }
                if (!in_array(strval($param['class']),$features)) {
                    array_push($features,strval($param['class']));
                }
                $member->update(['features'=>json_encode($features)],['id'=>$vs['id']]);
                array_push($carr,strval($vs['id']));
                $dnum++;
            }else{
                $wnum++;
            }


        }
        $clss->update(['features'=>json_encode($carr)],['id'=>$param['class']]);
        return message($dnum."条导入成功，".$wnum."条导入失败");
    }

}
